package common;

import java.util.LinkedList;
import java.util.Map;
import java.util.TreeMap;
import localization.Localization;
import localization.LocalizationResource;
import parsers.XmlParser;
import templates.Template;

public final class Application {

    public static final String PATH = "DatabaseAdminProEx\\application.xml";
    private static volatile Application instance;
    private static Map<Short, SortingStyle> sortingMap;
    private static String title;
    private static String connectionString;
    private static Iterable<Template> templateCollection;
    private static Localization localization;

    private Application() {
        templateCollection = new LinkedList<Template>();
        sortingMap = new TreeMap<Short, SortingStyle>();
    }

    public static Application getInstance() {
        if (instance == null) {
            synchronized (Application.class) {
                if (instance == null) {
                    instance = new Application();
                    Initializer in = new XmlParser(PATH);
                    in.setManagedObject(Initializer.ObjectType.Application);
                    Map<String,Object> map = (Map<String,Object>)in.init(instance);
                    title = (String) map.get("title");
                    connectionString = (String) map.get("connectionString");
                    templateCollection=(Iterable<Template>) map.get("templates");
                    for (Template t: templateCollection) {
                        sortingMap.put(t.getUid(), new SortingStyle());
                    }
                    localization=new Localization();
                    Iterable<LocalizationResource> itlocr= (Iterable<LocalizationResource>) map.get("localizations");
                    localization.setResources(itlocr);
                    //LocalizationResource a=itlocr.iterator().next().getUid();
                    localization.bind(itlocr.iterator().next().getUid());
                }
            }
        }
        return instance;
    }

    public String getTitle() {
        return title;
    }

    public Template getTemplate(short uid) {
        Template result = null;
        for (Template t: templateCollection) {
            if (uid == t.getUid()) {
                result = t;
                break;
            }
        }
        return result;
    }

    public Iterable<Template> getTemplateCollection(){
        return templateCollection;
    }

    public String getConnectionString() {
        return connectionString;
    }

    public SortingStyle getSortingStyle(short uid) {
        SortingStyle result = null;
        short templateUid = (short) (uid & 0xff00);
        if (sortingMap.containsKey(templateUid))
            result = sortingMap.get(templateUid);
        return result;
    }
}
